package com.valsong.sandbox.mock.repository;

import com.valsong.sandbox.mock.MockConfig;
import com.valsong.sandbox.mock.MockConfigRepository;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * AbstractMockConfigRepository
 *
 * @author Val Song
 */
@Slf4j
public abstract class AbstractMockConfigRepository implements MockConfigRepository {

    private volatile List<MockConfig> mockConfigList;

    @Override
    public void initMockConfigs(Map<String, String> param) {

        if (mockConfigList == null || mockConfigList.isEmpty()) {
            synchronized (AbstractMockConfigRepository.class) {
                if (mockConfigList == null || mockConfigList.isEmpty()) {
                    doInitMockConfigs(param);
                }
            }
        }
    }

    /**
     * 初始化Mock方法匹配规则
     *
     * @param param 参数
     */
    protected abstract void doInitMockConfigs(Map<String, String> param);

    /**
     * 设置 Mock方法匹配规则
     *
     * @param mockConfigList Mock方法匹配规则
     */
    protected void MockConfigs(List<MockConfig> mockConfigList) {
        this.mockConfigList = mockConfigList;
    }

    @Override
    public List<MockConfig> findAllMockConfigs() {
        if (mockConfigList == null || mockConfigList.isEmpty()) {
            return Collections.emptyList();
        }
        return mockConfigList.stream()
                .filter(Objects::nonNull)
                .filter(MockConfig::getEnable)
                .collect(Collectors.toList());
    }

}
